package fons.model.query.fun;

import java.util.List;

import com.google.common.collect.Lists;

public class CompareFun implements Function {
	private final Comparator comp;
	private final List<Function> list;
	
	public CompareFun (Comparator comp) {
		this(comp, null);
	}
	
	public CompareFun (Comparator comp, List<Function> list) {
		this.comp = comp;
		this.list = list;
	}
	
	@Override
	public Function apply(Function other) {		
		if (other instanceof ListFun) {
			if (list != null)
				throw new IllegalArgumentException("comparator can only be applied on a single list!");
			return new CompareFun(comp, Lists.newLinkedList(((ListFun) other).get()));
		
		} else {
			List<Function> newList = Lists.newLinkedList();
			if (list != null) newList.addAll(list);
			newList.add(other);
			return new CompareFun(comp, newList);
		}
		
	}

	@Override
	public Function apply() {
		Number last = null;
		
		if (list == null) return this;
		
		for (Function fun: list) {
			if (last == null) last = (Number) fun.apply();
			else {
				if (!comp.compare(last, (Number) fun.apply()))
					return BooleanFun.False;
				last = (Number) fun;
			}
		}
		return BooleanFun.True;
	}

}
